import React, { forwardRef,useEffect,useState } from 'react'
import { Form, Input, Select } from 'antd'

const { Option } = Select;

const UserForm = forwardRef((props,ref) => {
  const [isDisabled,setisDisabled]=useState(false)
  const {roleId,region}=JSON.parse(localStorage.getItem("token"))
  const roleObj={
    "1":"superadmin",
    "2":"admin",
    "3":"editor",
  }
  useEffect(()=>{
    setisDisabled(props.isDisabled)
  },[props.isDisabled])
  const regionSelect=(item)=>{
    if(roleObj[roleId]==="superadmin"){
      return false;
    }else{
      if(region===item.value){
        return false;
      }
      return true;
    }
  }
  const roleSelect=(item)=>{
    if(roleId===1){
      return false
    }else{
      if(roleId<item.id){
        return false
      }
      return true;
    }
  }
  return (
    <Form
      ref={ref}
      layout="vertical"
    >
      <Form.Item
        name="username"
        label="用户名"
        rules={[
          {
            required: true,
            message: '请输入用户名!',
          },
        ]}
      >
        <Input />
      </Form.Item>
      <Form.Item
        name="password"
        label="密码"
        rules={[
          {
            required: true,
            message: '请输入密码!',
          },
        ]}
      >
        <Input type="password" />
      </Form.Item>
      <Form.Item
        name="region"
        label="区域"
        rules={isDisabled?[]:[
          {
            required: true,
            message: '请选择区域!',
          },
        ]}
      >
        <Select disabled={isDisabled}>
          {
            props.regionsList.map(item => {
              // console.log(item);
              return <Option value={item.value} key={item.id} disabled={regionSelect(item)}>{item.title}</Option>
            })
          }
        </Select>
      </Form.Item>
      <Form.Item
        name="roleId"
        label="角色"
        rules={[
          {
            required: true,
            message: '请选择角色!',
          },
        ]}
      >
        <Select
          onChange={(value) => {
            if(value===1){
              setisDisabled(true)
              ref.current.setFieldsValue({
                region:''
              })
            }else{
              setisDisabled(false)
            }
          }}
        >
          {
            props.rolesList.map(item => {
              // console.log(item);
              return <Option value={item.id} key={item.id} disabled={roleSelect(item)}>{item.roleName}</Option>
            })
          }
        </Select>
      </Form.Item>
    </Form>
  )
})

export default UserForm